/**
 * ====================================
 *                ReadMe
 * 1. axios的配置文件
 * 2. 需要导出axios至main.js注册
 * ====================================
 */

//导入axios
import axios from 'axios'
import {Loading, Message} from 'element-ui'
import router from "@/router";

const service = axios.create({
    baseURL: 'http://106.53.125.141/admin',
    // baseURL: '/admin',
    timeout: 10000
})
let loading
// axios设置请求拦截器,设置响应头token
service.interceptors.request.use(
    config => {
        // console.log(config)

        //是否显示加载中
        if (config.loading) {
            //显示加载中
            loading = Loading.service({
                lock: true,
                text: '加载中',
                background: 'rgba(0, 0, 0, 0.3)'
            })
        }


        if (config.url.indexOf('auth') != -1) {
            //判断token不存在跳转login
            if (!localStorage.getItem('token')) {
                Message({
                    type: "error",
                    message: '请先登录'
                })
                router.push('/login')
            }
            config.headers['token'] = localStorage.getItem('token')
        }
        return config
    },
    err => {
        return Promise.reject(err)
    }
)

//响应拦截器
service.interceptors.response.use(
    success => {
        loading?.close()


        if (success.status.code == 200 && success.config.showMessage) {
            Message({
                type: 'success',
                showClose: true,
                message: success.data.msg
            })
        }
        if (success.status.code == 500) {
            Message({
                type: 'error',
                showClose: true,
                message: success.data.msg
            })
        }


        return success
    },
    err => {
        loading?.close()
        Message({
            type: "error",
            message: err.response.data.message
        })
        return Promise.reject(err)
    },
    (config) => {
        // console.log(config)
    }
)

export default service
